package com.liang.auth.application.controller;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.google.common.base.Preconditions;
import com.liang.auth.application.convert.AuthUserDTOConverter;
import com.liang.auth.api.entity.AuthUserDTO;
import com.liang.auth.api.entity.Result;
import com.liang.auth.domain.bo.AuthUserBO;
import com.liang.auth.domain.service.AuthUserDomainService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/user")
@RequiredArgsConstructor
public class UserController {

    private final AuthUserDomainService authUserDomainService;

    /**
     * 注册
     */
    @PostMapping("/register")
    public Result<Boolean> register(@RequestBody AuthUserDTO authUserDTO) {
        log.info("UserController.register.dto:{}", JSONUtil.toJsonStr(authUserDTO));
        try {
            Preconditions.checkNotNull(authUserDTO.getUsername(), "用户名不能为空");
            Preconditions.checkNotNull(authUserDTO.getPassword(), "密码不能为空");

            AuthUserBO authUserBO = AuthUserDTOConverter.INSTANCE.convertDTO2BO(authUserDTO);
            authUserDomainService.register(authUserBO);
            return Result.ok(true, "用户注册成功");
        } catch (Exception e) {
            log.error("UserController.register.error：{}", e.getMessage(), e);
            return Result.fail("用户注册失败");
        }
    }

    /**
     * 修改用户信息
     */
    @PostMapping("/update")
    public Result<Boolean> update(@RequestBody AuthUserDTO authUserDTO) {
        log.info("UserController.update.dto:{}", JSONUtil.toJsonStr(authUserDTO));
        try {
            Preconditions.checkNotNull(authUserDTO.getUsername(), "用户名不能为空");
            AuthUserBO authUserBO = AuthUserDTOConverter.INSTANCE.convertDTO2BO(authUserDTO);
            authUserDomainService.update(authUserBO);
            return Result.ok(true, "修改用户信息成功");
        } catch (Exception e) {
            log.error("UserController.update.error：{}", e.getMessage(), e);
            return Result.fail("修改用户信息失败");
        }
    }

    /**
     * 删除用户
     */
    @DeleteMapping("/delete")
    public Result<Boolean> delete(@RequestBody AuthUserDTO authUserDTO) {
        log.info("UserController.delete.dto:{}", JSONUtil.toJsonStr(authUserDTO));
        try {
            Long id = authUserDTO.getId();
            Preconditions.checkNotNull(id, "用户id不能为空");
            authUserDomainService.removeById(id);
            return Result.ok(true, "删除用户成功");
        } catch (Exception e) {
            log.error("UserController.delete.error：{}", e.getMessage(), e);
            return Result.fail("删除用户失败");
        }
    }

    /**
     * 用户启用/禁用
     */
    @PostMapping("/changeStatus")
    public Result<Void> changeStatus(@RequestBody AuthUserDTO authUserDTO) {
        log.info("UserController.changeStatus.dto:{}", JSONUtil.toJsonStr(authUserDTO));
        try {
            Preconditions.checkNotNull(authUserDTO.getId(), "用户id不能为空");
            Integer status = authUserDTO.getStatus();
            Preconditions.checkNotNull(status, "用户状态不能为空");
            AuthUserBO authUserBO = AuthUserDTOConverter.INSTANCE.convertDTO2BO(authUserDTO);
            authUserDomainService.update(authUserBO);
            return status == 0 ? Result.ok("启用用用户成功") : Result.ok("禁用用户成功");
        } catch (Exception e) {
            log.error("UserController.changeStatus.error：{}", e.getMessage(), e);
            return Result.fail("用户启用/禁用用户失败");
        }
    }

    /**
     * 获取用户信息
     */
    @PostMapping("/getUserInfo")
    public Result<AuthUserDTO> getUserInfo(@RequestBody AuthUserDTO authUserDTO) {
        log.info("UserController.getUserInfo.dto:{}", JSONUtil.toJsonStr(authUserDTO));
        try {
            Preconditions.checkNotNull(authUserDTO.getUsername(), "用户名不能为空");
            AuthUserBO authUserBO = AuthUserDTOConverter.INSTANCE.convertDTO2BO(authUserDTO);
            authUserBO = authUserDomainService.getUserInfo(authUserBO);
            return Result.ok(AuthUserDTOConverter.INSTANCE.convertBO2DTO(authUserBO));
        } catch (Exception e) {
            log.error("UserController.getUserInfo.error：{}", e.getMessage(), e);
            return Result.fail("获取用户信息失败");
        }
    }

    /**
     * 批量获取用户信息
     */
    @RequestMapping("listByIds")
    public Result<List<AuthUserDTO>> listUserInfoByIds(@RequestBody List<String> usernameList) {
        try {
            if (log.isInfoEnabled()) {
                log.info("UserController.listUserInfoByIds.dto:{}", JSON.toJSONString(usernameList));
            }
            Preconditions.checkArgument(!CollectionUtils.isEmpty(usernameList), "id集合不能为空");
            List<AuthUserBO> userInfos = authUserDomainService.listUserInfoByNames(usernameList);
            List<AuthUserDTO> res = AuthUserDTOConverter.INSTANCE.convertBOToDTO(userInfos);
            return Result.ok(res);
        } catch (Exception e) {
            log.error("UserController.listUserInfoByIds.error:{}", e.getMessage(), e);
            return Result.fail("批量获取用户信息失败");
        }
    }


    /**
     * 登录
     */
    @RequestMapping("/doLogin")
    public Result<SaTokenInfo> doLogin(@RequestParam String validCode) {
        try {
            Preconditions.checkArgument(StrUtil.isNotBlank(validCode), "验证码不能为空");
            SaTokenInfo tokenInfo = authUserDomainService.doLogin(validCode);
            return Result.ok(tokenInfo, "登录成功");
        } catch (Exception e) {
            return Result.fail("登录失败");
        }
    }

    /**
     * 退出登录
     */
    @RequestMapping("/logout")
    public Result<Void> logout(@RequestParam String username) {
        try {
            log.info("UserController.logout.username:{}", username);
            Preconditions.checkArgument(StrUtil.isNotBlank(username), "用户名不能为空");
            StpUtil.logout(username);
            return Result.ok("退出登录成功");

        } catch (Exception e) {
            log.error("UserController.logout.error：{}", e.getMessage(), e);
            return Result.fail("退出登录失败");
        }
    }

    // 查询登录状态，浏览器访问： http://localhost:8081/user/isLogin
    @RequestMapping("/isLogin")
    public String isLogin() {
        return "当前会话是否登录：" + StpUtil.isLogin();
    }

}
